/**
 * 功能：提现
 * 入口：转入银行卡
 * 
 */
import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import HomeHeader from '../../components/Header/index.jsx'
import {DanluJsBridge,filter,logger,http} from 'common/index'
import {Alert,PullLoad,Header} from 'components/index'
import FormInput from 'components/FormInput/index.jsx'
import {CheckPassword,Caption,BankCard,NoCard} from './subpage/index'
 import { hashHistory ,Link,browserHistory} from 'react-router'
// redux
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as walletInfoActionsFromOtherFile from '../../store/actions/walletinfo' 

import Enume from './enume'

class Deposit extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            balance : {},
            amount : '',
            isDeposited:false,
            havePassword:false,
            showAutoDeposit:true,
            showCheckPasswd : false,
            autoDeposit : false,
            choosedCard:'',   //选中的银行卡号
            bindCards : props.walletinfo.bindCards,
            depositDisabled:true, //禁止按钮点击
            errorInfo : ''
        }
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    }
   
    componentWillMount (){
        //初始化标题
        DanluJsBridge.callHandler('setTitle', {
                title: '提现',
                color: '#ffffffff',
            }, function(response) {
        })
        DanluJsBridge.callHandler("setBackBtnColor", {
          color: '#ffffffff'
        });
        DanluJsBridge.callHandler('setTitleBarColor', {
            color: ['#fffc7646','#fff5a466']
        }, function() {
            alert(123)
        })
        var _this = this;
        
        //是否设置过支付密码
        var showAutoDeposit = !(this.props.walletinfo.user.roleType == 'dlzdd')
        //判断是否选择过银行卡
        var choosedCard = ""
        if(this.props.location.state.acc_type == '208'){
            this.state.bindCards.map(bank =>{
                //对公卡号
                if (bank.cardType == '3' && !choosedCard) {
                    choosedCard = bank
                }
            })
        }else if (this.props.walletinfo.choosedCard) { //重新选择的银行卡
            choosedCard = _this.props.walletinfo.choosedCard
        }else {  //默认的对私卡号
            this.state.bindCards.map(bank =>{ 
                //对公卡号
                if (bank.cardType != '3' && !choosedCard) {
                    choosedCard = bank
                }
            })
        }

        this.getAutoWithDrawConfig();

        this.setState({
            choosedCard : choosedCard,
            showAutoDeposit : showAutoDeposit,
            havePassword: this.props.walletinfo.havePassword 
          });
        
    }
    //获取自动提现开关
    getAutoWithDrawConfig(){
        var reqData = {
            companyId : this.props.walletinfo.user.companyId || ''
        }
        http.post('/dlpcweb/dlpc/pc/V1/wallet/getAutoWithDrawConfig',reqData).then((data) =>{
            var autoDeposit = !!(data.autoSwitch == '1')
            this.props.walletinfoActions.walletInfoUpdate({
                title: "自动提现开关状态",
                autoDeposit : autoDeposit,
                publicCardId : data.publicCardId,
                privateCardId : data.privateCardId
            })
            this.setState({
                autoDeposit : autoDeposit,

            })

        })
    }
    //查询余额
    getBalance (){
        var _this = this;
        return new Promise(function(resolve,reject){
             var reqData = {
                "userId": _this.props.walletinfo.user.userId,
                "companyId": _this.props.walletinfo.user.companyId
            }
            http.post('/dlpcweb/dlpc/pc/V1/wallet/getBalance',reqData).then((data) =>{
                var balanceDetail = data.balanceDetail || []
                _this.props.walletinfoActions.walletInfoUpdate({
                    balanceDetail : balanceDetail,
                    withDrawFee : data.withDrawFee
                })
                resolve();
            }).catch(function(e){
                resolve();
            })           
        })
    }

    bankCardClick(card){
        if (this.props.location.state.acc_type !='209') {
            return 
        }
        var depositDisabled = this.state.amount > filter.toMoney(this.state.balance.avl_bal) || !this.state.amount || !this.state.choosedCard
        this.setState({
            choosedCard : card,
            userBusiId : card.userBusiId,
            depositDisabled : depositDisabled
        })

        this.props.walletinfoActions.walletInfoUpdate({
            choosedCard : card
        })
        //跳转到银行卡列表页
        hashHistory.push({
            pathname:'bankCardList',
            query:{
                acc_type:'209'
            }
        });
    }

    amountValidate (value,callback){
        
    }


    //金额改变
    amountChange (value){
        var errorInfo = ''
        var depositDisabled = false
        if (!parseFloat(value)) {
            errorInfo = "请输入金额";
            depositDisabled = true
        }else if (parseFloat(value)<0) {
            errorInfo = "金额格式不正确";
            depositDisabled = true
        }else if(value.split(".").length>1 && value.split(".")[1].length >2){
            errorInfo = '仅支持小数点后两位'
            depositDisabled = true
        }else if(this.state.balance.avl_bal - value*100 < 0){
            errorInfo = '金额不可超过可用余额';
            depositDisabled = true
        }else if(this.state.balance.avl_bal - this.props.walletinfo.withDrawFee - value*100 < 0){
            errorInfo = '提现金额需小于扣减服务费后的剩余金额';
            depositDisabled = true
        }
        this.setState({
            amount : value,
            errorInfo :errorInfo,
            depositDisabled :depositDisabled
        })
    }
    //校验密码
    ValidatePassword (){
        this.setState({
            showCheckPasswd : true
        })
    }
    cancel (){
        this.setState({
            showCheckPasswd : false
        })
    }
    drawAll (){
        this.setState({
            amount : (this.state.balance.avl_bal - this.props.walletinfo.withDrawFee )/100,
            depositDisabled : false,
            errorInfo : ''
        })
    }
    //确认提现接口
    withDraw (){
        var _this = this;
        this.setState({
                depositDisabled : true,
                showCheckPasswd : false,
            })
        var userBusiId = this.state.choosedCard.userBusiId
        var reqData = {
            "userId": this.props.walletinfo.user.userId,
            "companyId": this.props.walletinfo.user.companyId,
            "amount": (this.state.amount*100).toString(),
            "accType": this.state.balance.acc_type,
            "userBusiId": userBusiId
        }
        http.post('/dlpcweb/dlpc/pc/V1/wallet/withDraw',reqData).then( data => {
            // 提现申请成功
            this.setState({
                isDeposited : true
            })
        }).catch(function(err){
            _this.getBalance();
            _this.setState({
                amount : '',
                depositDisabled : true
            })
        })
    }
    //提现金额限制规则
    moneyChangeRule (value){

        // 限制小数点两位
        if (value && value.indexOf('.')>0 ) {
            var decimals = value.split('.')[1];
            // 保留小数点后两位
            if (decimals.length >2) {
                value =  parseInt(value*100)/100
            }
        }
        // 限制长度
        if (value.toString().length >12) {
            value = value.substring(0,12)
        }
        return value.toString()
    }
    // 返回上一级
    goBack(){
        browserHistory.goBack()
    }
    render() {
        //选中的银行卡
        var balanceDetail= this.props.walletinfo.balanceDetail || []
        var balance = ""
        balanceDetail.forEach(item =>{
            if (item.acc_type ==  this.props.location.state.acc_type) {
                balance = item
            }
        })
        this.state.balance = balance
        return (
        	<div className="Deposit">
                    <HomeHeader  className="wallet-hader" />
                    {/* 弹窗 */}
                    {
                        this.state.showCheckPasswd == true ? (
                            <CheckPassword havePassword={this.state.havePassword} validate={this.withDraw.bind(this)} cancel={this.cancel.bind(this)} userId={this.props.walletinfo.user.userId}/>
                        ) : ''
                    }
                    <div className="wallet-hader">
                        <div className="align-center wallet-account">
                            <div className="inline-block TranItem"  >
                                <img src={require('static/image/wallet-person.png')} alt="" />
                            </div>
                            <div className="inline-block TranItem"  >
                                <img src={require('static/image/wallet-transfer.png')} alt="" />
                            </div>
                            <div className="inline-block TranItem"  >
                                <img src={require('static/image/wallet-company.png')} alt="" />
                            </div>
                        </div>
                        {
                            this.state.isDeposited === false ? <div className="align-center padding10">
                            {Enume.accType[balance.acc_type]}
                        余额提现</div> : ''
                        }
                        
                    </div>
                    
                    {
                      this.state.isDeposited === true ? ( <div>
                            <div className="padding10" style={{background:'#fff'}}>
                                <span>提现申请已提交，请等待处理结果</span>
                            </div>
                            <div className="padding10" style={{borderTop:'1px solid lightgray',background:'#fff'}}>
                                <div>
                                    <span>明细：{Enume.accType[balance.acc_type]}余额提现</span>
                                </div>
                                <div>
                                    <span>金额：</span><span style={{color:'#fc7646'}}>¥ {filter.toMoneyFormat(this.state.amount*100)}</span>
                                </div>
                            </div>

                            <div className="complete-btn bind-btn">
                                <button className="sure-btn " onClick={this.goBack.bind(this)}> 完 成 </button>
                            </div>
                        </div>) : (<div>
                            {
                                <div>
                                    <div className="padding10">
                                        <span className="gray">提现至：</span>
                                    </div>
                                    {
                                        this.state.choosedCard ? <BankCard card={this.state.choosedCard} showMore={ this.props.location.state.acc_type == '209' } onClick={this.bankCardClick.bind(this)}/> : <NoCard showMore={ this.props.location.state.acc_type == '209' }/>
                                    }
                                    
                                    
                                    <div style={{height:10}}></div>
                                    <div >
                                        <FormInput placeholder="请输入提现金额  " type="number" pattern="/[^a-zA-Z]/" value={this.state.amount} changeRule={this.moneyChangeRule.bind(this)} onChange={this.amountChange.bind(this)}/>
                                        {
                                            this.state.errorInfo ? (
                                                <div className="form-warning">
                                                    {this.state.errorInfo}
                                                </div>
                                            ): ''
                                        }
                                    </div>
                                    <div className="padding10">
                                        <div className="inline-block gray">
                                            可提金额：{filter.toMoneyFormat(balance.avl_bal)}
                                        </div>
                                        <div className="inline-block float-right">
                                            <button className="wallet-color btn-text" disabled={ !this.state.choosedCard || (balance.avl_bal <= this.props.walletinfo.withDrawFee)  } onClick={this.drawAll.bind(this)}>全部提现</button>
                                        </div>
                                    </div>
                                    {
                                        this.state.showAutoDeposit ? <div className="padding10 autoDeposit-bar">
                                            <Link  to={{pathname:'/autoDeposit',state:{acc_type:balance.acc_type}}}>自动提现已
                                            {this.state.autoDeposit ? '开启' : '关闭'}
                                                <div className="float-right gray">提现设置 <i className="iconfont icon-right"/></div>
                                             </Link>
                                        </div> : ''
                                    }
                                    
                                    <div className="padding10  deposit-btn">
                                        <div className="padding5 gray" >提示：每次提现将收取
                                            <span className="wallet-color">{filter.toMoneyFormat(this.props.walletinfo.withDrawFee)}</span>
                                        元服务费</div>
                                        <button className='sure-btn' disabled={this.state.depositDisabled}  onClick={this.ValidatePassword.bind(this)}>确认提现</button>
                                    </div>
                                    
                                </div>

                            }
                        </div>) 
                    }
                    

        	</div>
        )
    }
}


// -------------------redux react 绑定--------------------

function mapStateToProps(state) {
    return {
        walletinfo: state.walletinfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        walletinfoActions: bindActionCreators(walletInfoActionsFromOtherFile, dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Deposit)
